<template>
    <div class="create-template-image">
        <iframe 
            :id="`${projectId}topoProject`"
            class="iframe"
            :src="`/14-topologyProject/#/topoShowInTestReport?projectId=${projectId}`"
            @load="uploadTopoFile"></iframe>
    </div>
</template>

<script>
import html2canvas from 'html2canvas'
import { uploadFiles } from '@/api/compitionStatic'

export default {
    name: 'CreateTemplateImage',
    props: {
        projectId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
        }
    },
    methods: {
        // 绘制工程
        async uploadTopoFile(){
            /**
             * 1.此时已加载完成，用canvas生成图片,由于html2canvas无法获取跨域的内容，所以使用
             * postmessage事件监听来获取数据
             */
            let _this = this;
            let projectId = this.projectId
            let page = document.getElementById(`${projectId}topoProject`)
            setTimeout(() => {
                page.contentWindow.getCanvasData();
            }, 10*1000)
            window.addEventListener('message', function(event) {
                if(event.source === page.contentWindow){
                    var canvas = event.data;
                    let canvasEl = document.createElement('canvas');
                    canvasEl.width = canvas.width;
                    canvasEl.height = canvas.height;
                    canvasEl.id = projectId+'canvas';
                    let ctx = canvasEl.getContext('2d');
                    ctx.putImageData(canvas, 0, 0);
                    document.body.appendChild(canvasEl);
                    setTimeout(async ()=>{
                        let canvasElement = document.getElementById(`${projectId}canvas`)
                        let canvasImage = await html2canvas(canvasElement, { useCORS: true }); // 配置允许跨域
                        let file = canvasImage.toDataURL('image/png');
                        _this.createImg = file;
                        let formData = new FormData();
                        let blob = _this.dataURLtoFile(file,'image/jpeg');
                        let fileOfBlob = new File([blob],`${projectId}-${new Date().getTime()}.png`);
                        formData.append('file',fileOfBlob);
                        try {
                            uploadFiles(formData).then(res=>{
                                if(res.code==1){
                                    let filePath = res.data;
                                    let fileId = res.info.id;
                                    document.getElementById(`${projectId}canvas`).remove();
                                    _this.$emit('upload-image-succes', {
                                        imageId: fileId,
                                        imagePath: filePath
                                    })
                                } else {
                                    document.getElementById(`${projectId}canvas`).remove();
                                    _this.$emit('upload-image-error')
                                }
                            }).catch(() => {
                                document.getElementById(`${projectId}canvas`).remove();
                                _this.$emit('upload-image-error')
                            })
                        } catch (error) {
                            document.getElementById(`${projectId}canvas`).remove();
                            _this.$emit('upload-image-error')
                        }
                    }, 10*1000)
                }
            });
        },
        dataURLtoFile(dataURI, type) {
            var  binary = atob(dataURI.split(',')[1]);
            var  array = [];
            for (var  i = 0; i < binary.length; i++) {
                array.push(binary.charCodeAt(i));
            }
            return new Blob([new Uint8Array(array)], { type: type });
        },
    }
}
</script>

<style scoped>
.create-template-image {
    position: absolute;
    left: 0;
    top: 0;
    z-index: -10;
    width: 100%;
    height: 100%;
}
</style>